<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Employees extends CI_Controller
{
	function __construct()
	{
		parent::__construct();		
		if (!$this->tank_auth->is_logged_in()) redirect('auth/login');				
		
		//load models
		$this->load->model('Employees_db');
		$this->load->model('teams/Teams_db');
		$this->load->model('positions/Positions_db');
		$this->load->model('leaves/Leaves_db');
	}
	
	/*VIEW FUNCTIONS*/
	function index()
	{	
		redirect('employees/manage');
	}
	function add()
	{
		//default
		$data['ptitle'] = "Add Employee";				
		$data['username'] = $this->tank_auth->get_username();
		$data['module'] = 'employees';
		$data['active_header'] = 'admin';
		//end default
		
		//dropdowns
		$data['roles'] = $this->Default_db->getRoles();
		$data['genders'] = $this->Default_db->getGenders();
		$data['shifts'] = $this->Default_db->getShifts();
		$data['empstatus'] = $this->Default_db->getEmployeeStatus();
		$data['groups'] = $this->Teams_db->getTeams();
		$data['positions'] = $this->Positions_db->getPositions();
		
		$data['content'] = $this->load->view('add',$data,true);		
		$this->load->view('default_view',$data);
	}
	
	function manage()
	{
		//default
		$data['ptitle'] = "Manage Employees";				
		$data['username'] = $this->tank_auth->get_username();
		$data['module'] = 'employees';
		$data['active_header'] = 'admin';
		//end default		
		
		$data['content'] = $this->load->view('manage',$data,true);		
		$this->load->view('default_view',$data);
	}
	
	function edit($id)
	{		
		//default
		$data['ptitle'] = "Edit Employee";				
		$data['username'] = $this->tank_auth->get_username();
		$data['module'] = 'employees';
		$data['active_header'] = 'admin';
		//end default
		
		//dropdowns
		$data['roles'] = $this->Default_db->getRoles();
		$data['genders'] = $this->Default_db->getGenders();
		$data['shifts'] = $this->Default_db->getShifts();
		$data['empstatus'] = $this->Default_db->getEmployeeStatus();
		$data['groups'] = $this->Teams_db->getTeams();		
		
		//check employee if existing
		$emp = $this->Employees_db->getEmployee(array('id'=>$id));
		if(!count($emp)) show_404('page');
		
		//dropdown
		$data['positions'] = $this->Positions_db->getPositions();
		
		$data['item'] = $id;
		$data['content'] = $this->load->view('edit',$data,true);		
		$this->load->view('default_view',$data);
	}
	
	function profile($id)
	{
		if($id==$this->tank_auth->get_user_id())
		{
			//default
			$data['ptitle'] = "My Profile";				
			$data['username'] = $this->tank_auth->get_username();
			$data['module'] = 'employees';
			$data['active_header'] = 'admin';
			//end default
			
			//dropdowns
			$data['roles'] = $this->Default_db->getRoles();
			$data['genders'] = $this->Default_db->getGenders();
			$data['shifts'] = $this->Default_db->getShifts();
			$data['empstatus'] = $this->Default_db->getEmployeeStatus();
			$data['groups'] = $this->Teams_db->getTeams();		
			
			//check employee if existing
			$emp = $this->Employees_db->getEmployee(array('id'=>$id));
			if(!count($emp)) show_404('page');
			
			//dropdown
			$data['positions'] = $this->Positions_db->getPositions(array('group_id'=>$emp[0]['group_id']));
			
			$data['item'] = $id;
			$data['content'] = $this->load->view('profile',$data,true);		
			$this->load->view('default_view',$data);
		}
		else
			show_404('page');
	}
		
	/*END VIEW FUNCTIONS*/
	
	
	/* AJAX FUNCTIONS */
	function addItem()
	{
		$dt = null;
		$error = false;
		foreach($_POST as $name => $value) {
			if (isset($_POST[$name])) $dt[$name] = $this->input->post($name);
		}
		//validate employee no, email, and empID
		$emp = $this->Employees_db->validateUniqueValues($dt['employee_no'], $dt['username'], $dt['email']);		
		$error = count($emp)== 0 ? false : true;
		if($error) { echo json_encode(array('return'=>'error')); return; }
			
		//remove image arrays
		if($dt['image_name'])  $image_name = $dt['image_name'];
		unset($dt['image_name']);

		if($dt['image_size']) $image_size = $dt['image_size'];
		unset($dt['image_size']);

		if($dt['image_data']) $image_data = $dt['image_data'];
		unset($dt['image_data']);
			
		
		//set additional data
		$now = date('Y-m-d H:i:s');
		$dt['created'] = $now;
		$dt['created_by'] = $dt['modified_by'] = $this->tank_auth->get_user_id();
		$dt['password'] = $this->tank_auth->hash_password($dt['password']);
		$dt['middle_initial'] = strtoupper(substr($dt['middlename'], 0 , 1));
		$dt['fullname'] = $dt['lastname'].', '.$dt['firstname'].' '.$dt['middle_initial'].'.';		
		$dt['date_hired'] = ($dt['date_hired']) ? $this->members_pi->convertDate($dt['date_hired']) : '';
		$dt['regularization_date'] = ($dt['regularization_date']) ? $this->members_pi->convertDate($dt['regularization_date']) : '';
		$dt['resignation_date'] = ($dt['resignation_date']) ? $this->members_pi->convertDate($dt['resignation_date']) : '';
		$dt['birthday'] = ($dt['birthday']) ? $this->members_pi->convertDate($dt['birthday']) : '';
		
		$item = $this->Employees_db->save($dt);
		
		//add leaves
		$this->Leaves_db->addLeavesToEmployee($dt['employee_status_id'], $dt['gender_id'], $this->tank_auth->get_user_id(), $item);
		
		//save image
		if(isset($image_name))
		{
			$dtImg = array('image_name'=>$image_name, 'image_size'=>$image_size, 'image_data'=>base64_decode($image_data));
			$imgid = $this->Default_db->saveImage($dtImg);
			
			//update user table, set image id
			$this->Employees_db->save(array('image_id'=>$imgid),$item);
			
			//audit trail
			$this->Audittrail_db->save(array('module'=>'images', 'item_id'=>$imgid, 'action'=>'add', 'description'=>serialize($dtImg), 'created'=>$now, 'created_by'=>$this->tank_auth->get_user_id()));
		}
		
		
		//send email
		//code here
		
		//audit trail
		$this->Audittrail_db->save(array('module'=>'employees', 'item_id'=>$item, 'action'=>'add', 'description'=>serialize($dt), 'created'=>$now, 'created_by'=>$this->tank_auth->get_user_id()));
		
		echo json_encode(array('return'=>'success'));
		return;
	}
	
	function viewItem()
	{
		$dt['id'] = $this->input->post('item');
		$details = $this->Employees_db->getEmployee($dt);
		if ($details)
		{
			$details[0]['date_hired'] = ($details[0]['date_hired']) ? $this->members_pi->convertDateDisplay($details[0]['date_hired'],false,'') : '';
			$details[0]['regularization_date'] = ($details[0]['regularization_date']) ? $this->members_pi->convertDateDisplay($details[0]['regularization_date'],false,'') : '';
			$details[0]['resignation_date'] = ($details[0]['resignation_date']) ? $this->members_pi->convertDateDisplay($details[0]['resignation_date'],false,'') : '';
			$details[0]['birthday'] = ($details[0]['birthday']) ? $this->members_pi->convertDateDisplay($details[0]['birthday'],false,'') : '';
		
			echo json_encode($details);
		}
	}
	
	function updateItem()
	{	
		$id = $this->input->post('item');		
		$dt = null;
		$error = false;
		foreach($_POST as $name => $value) {
			if($name!='item')
				if (isset($_POST[$name])) $dt[$name] = $this->input->post($name);
		}
		//validate employee no, email, and empID
		$emp = array();
		if(isset($dt['employee_no']) && $dt['username'] && $dt['email'])
			$emp = $this->Employees_db->validateUniqueValues($dt['employee_no'], $dt['username'], $dt['email'], $id);		
		$error = count($emp)== 0 ? false : true;
		if($error) { echo json_encode(array('return'=>'error')); return; }
		
		//remove image arrays
		if($dt['image_name'])  $image_name = $dt['image_name'];
		unset($dt['image_name']);

		if($dt['image_size']) $image_size = $dt['image_size'];
		unset($dt['image_size']);

		if($dt['image_data']) $image_data = $dt['image_data'];
		unset($dt['image_data']);
					
		//set additional data
		$dt['modified_by'] = $this->tank_auth->get_user_id();
		$dt['modified'] = date('Y-m-d H:i:s');
		if(isset($dt['password']) && $dt['password']!="")
			$dt['password'] = $this->tank_auth->hash_password($dt['password']);
		else
			unset($dt['password']);
		$dt['middle_initial'] = strtoupper(substr($dt['middlename'], 0 , 1));
		$dt['fullname'] = $dt['lastname'].', '.$dt['firstname'].' '.$dt['middle_initial'].'.';
		if(isset($dt['date_hired'])) $dt['date_hired'] = ($dt['date_hired']) ? $this->members_pi->convertDate($dt['date_hired']) : '';
		if(isset($dt['regularization_date'])) $dt['regularization_date'] = ($dt['regularization_date']) ? $this->members_pi->convertDate($dt['regularization_date']) : '';
		if(isset($dt['resignation_date'])) $dt['resignation_date'] = ($dt['resignation_date']) ? $this->members_pi->convertDate($dt['resignation_date']) : '';
		if(isset($dt['birthday'])) $dt['birthday'] = ($dt['birthday']) ? $this->members_pi->convertDate($dt['birthday']) : '';

		$item = $this->Employees_db->save($dt, $id);
		
		//save image
		if(isset($image_name))
		{
			$dtImg = array('image_name'=>$image_name, 'image_size'=>$image_size, 'image_data'=>base64_decode($image_data));
			$imgid = $this->Default_db->saveImage($dtImg);
			
			//update user table, set image id
			$this->Employees_db->save(array('image_id'=>$imgid),$item);
			
			//audit trail
			$this->Audittrail_db->save(array('module'=>'images', 'item_id'=>$imgid, 'action'=>'add', 'description'=>serialize($dtImg), 'created'=>date('Y-m-d H:i:s'), 'created_by'=>$this->tank_auth->get_user_id()));
		}
		
		//send email
		//code here
		
		//audit trail
		$this->Audittrail_db->save(array('module'=>'employees', 'item_id'=>$item, 'action'=>'update', 'description'=>serialize($dt), 'created'=>$dt['modified'], 'created_by'=>$this->tank_auth->get_user_id()));
		
		echo json_encode(array('return'=>'success'));
		return;
	}
	
	function deleteItem()
	{
		$dt = $this->input->post('items');
		$item = $this->Employees_db->delete($dt);
		
		//audit trail
		foreach($dt as $d)
			$this->Audittrail_db->save(array('module'=>'employees', 'item_id'=>$d, 'action'=>'delete', 'description'=>serialize($dt), 'created'=>date('Y-m-d H:i:s'), 'created_by'=>$this->tank_auth->get_user_id()));
		
		echo json_encode(array('return'=>'success'));
		return;
	}
	
	
	
	function isEmpNoAvailable($id = false)
	{
		/* RECEIVE VALUE */
		$validateValue=$this->input->post('fieldValue');
		$validateId=$this->input->post('fieldId');
		
		/* RETURN VALUE */
		$arrayToJs = array();
		$arrayToJs[0] = $validateId;
		
		$emp = $this->Employees_db->getEmployee(array('employee_no'=>$validateValue), $id);
		$arrayToJs[1] = count($emp)==0 ? true : false;
		
		echo json_encode($arrayToJs);
	}
	
	function isUsernameAvailable($id = false)
	{
		/* RECEIVE VALUE */
		$validateValue=$this->input->post('fieldValue');
		$validateId=$this->input->post('fieldId');
		
		/* RETURN VALUE */
		$arrayToJs = array();
		$arrayToJs[0] = $validateId;
		
		$emp = $this->Employees_db->getEmployee(array('username'=>$validateValue), $id);
		$arrayToJs[1] = count($emp)==0 ? true : false;
		
		echo json_encode($arrayToJs);
	}
	
	function isEmailAvailable($id = false)
	{
		/* RECEIVE VALUE */
		$validateValue=$this->input->post('fieldValue');
		$validateId=$this->input->post('fieldId');
		
		/* RETURN VALUE */
		$arrayToJs = array();
		$arrayToJs[0] = $validateId;
		
		$emp = $this->Employees_db->getEmployee(array('email'=>$validateValue), $id);
		$arrayToJs[1] = count($emp)==0 ? true : false;
		
		echo json_encode($arrayToJs);
	}
	
	function listview()
	{
		$data = $this->Employees_db->getList();
		echo json_encode($data);
	}
	
	function upload($qqfile)
	{
		$this->load->helper('qqupload');
		$path = $_SERVER['DOCUMENT_ROOT'].'temp/';
		//chmod($path, 0755);
		if(!file_exists($path))
			mkdir($path);
		$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
		$sizeLimit = 1000 * 1024;
		$qqfile = date('YmdHis').'-'.$qqfile;
		$uploader = new qqFileUploader($allowedExtensions,$sizeLimit,$qqfile);
		$result = $uploader->handleUpload($path);
		echo json_encode(array('filename'=>$qqfile, 'image'=>$result));
	}
	/* END AJAX FUNCTIONS */
	
	
	/* LOAD MODULE JS */
	function js() {
        $this->load->view('js/script.js');
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */